package com.company.cloud.admin.modules.admin.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;

import com.company.cloud.admin.modules.cache.utils.PTUserConvertUtils;
import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.redis.service.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.admin.constant.PlatformAdminConstant;
import com.company.cloud.admin.constant.PlatformAdminErrorEnum;
import com.company.cloud.admin.modules.admin.controller.req.ManageUserAddParam;
import com.company.cloud.admin.modules.admin.controller.req.ManageUserQuery4PageParam;
import com.company.cloud.admin.modules.admin.controller.req.ManageUserUpdateInfoParam;
import com.company.cloud.admin.modules.admin.controller.req.UserInfoUpdatePasswordParam;
import com.company.cloud.admin.modules.admin.controller.req.UserInfoUpdateStateParam;
import com.company.cloud.admin.modules.admin.models.UserInfoModel;
import com.company.cloud.admin.modules.admin.service.UserManageMgrService;
import com.company.cloud.admin.modules.base.entity.DeptInfo;
import com.company.cloud.admin.modules.base.entity.UserManageInfo;
import com.company.cloud.admin.modules.base.entity.UserRoleInfo;
import com.company.cloud.admin.modules.base.service.DeptInfoService;
import com.company.cloud.admin.modules.base.service.UserManageInfoService;
import com.company.cloud.admin.modules.base.service.UserRoleInfoService;
import com.company.cloud.admin.modules.cache.service.UserPermissionCacheService;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.PasswordUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Authc
@RestController
@RequestMapping("/admin/userManage")
@Api(tags = "Admin_User_后管用户管理")
public class ManageUserMgrController {

	@Autowired
	private UserManageInfoService userManageInfoService;

	@Autowired
	private UserRoleInfoService userRoleInfoService;

	@Autowired
	private UserManageMgrService userManageMgrService;

	@Autowired
	private UserPermissionCacheService userPermissionCacheService;

	@Autowired
	private DeptInfoService deptInfoService;

	@Autowired
	private RedisUtils redisUtils;
	
	@GetMapping("/query")
	@ApiOperation(value="用户列表查询", response= UserInfoModel.class)
	public BaseResult query(ManageUserQuery4PageParam params) {
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		IPage<UserManageInfo> page =userManageInfoService.page(new Page<>(params.getPage(), params.getRows()),
				new QueryWrapper<UserManageInfo>()
				.eq(StringUtils.hasText(params.getUserState()), "user_state",params.getUserState())
				.like(StringUtils.hasText(params.getUserName()), "user_name", params.getUserName())
				.like(StringUtils.hasText(params.getNickName()), "nick_name", params.getNickName())
				.likeRight(StringUtils.hasText(params.getMobile()), "mobile", params.getMobile())
				);

		Set<Integer> deptIds=new HashSet<Integer>();
		if(page!=null && !CollectionUtils.isEmpty(page.getRecords())) {
			for(UserManageInfo item:page.getRecords()) {
				if(item.getDeptId()!=null) {
					deptIds.add(item.getDeptId());
				}
			}
		}

		IPage<UserInfoModel> data=page.convert(new Function<UserManageInfo, UserInfoModel>() {
			@Override
			public UserInfoModel apply(UserManageInfo entity) {
				return PTUserConvertUtils.getUserInfoModel(entity);
			}
		});
		return BaseResult.ok(data);
	}
	
	@PostMapping("/save")
	@ApiOperation(value="新增用户",response=BaseResult.class)
	@StaffLogc(title = "新增用户", action = "新增用户", actionAdo = "后台用户信息")
	public BaseResult save(@RequestBody ManageUserAddParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo  userInfo= AuthContextUtils.getUser();
		userManageMgrService.save(params,userInfo);
		return BaseResult.ok();
	}
	
	@PostMapping("/update")
	@ApiOperation(value="修改用户",response = BaseResult.class)
	@StaffLogc(title = "修改用户", action = "修改用户", actionAdo = "后台用户信息")
	public BaseResult update(@RequestBody ManageUserUpdateInfoParam params) {
		ValidatorUtils.validate(params);
		userManageMgrService.update(params,  AuthContextUtils.getUser());
		userPermissionCacheService.logoutUser(params.getId());
		return BaseResult.ok();
	}
	
	@GetMapping("/get")
	@ApiOperation(value="用户信息",response = UserInfoModel.class)
	public BaseResult get(@RequestParam("id")Integer id) {
		UserManageInfo userInfo= userManageInfoService.getById(id);
		if(userInfo==null) {
			throw new BusinessException(PlatformAdminErrorEnum.USER_NULL);
		}
		DeptInfo dept=null;
		if(CheckUtils.hasInt(userInfo.getDeptId())){
			dept=deptInfoService.getById(userInfo.getDeptId());
		}
		List<UserRoleInfo> userRoleList= userRoleInfoService.list(
				new QueryWrapper<UserRoleInfo>().eq("user_id", id));
		UserInfoModel data= PTUserConvertUtils.getUserInfoModel(userInfo,dept,userRoleList);
		return BaseResult.ok(data);
	}
	
	@PostMapping("/changeState")
	@ApiOperation(value="用户改变状态",response = BaseResult.class)
	@StaffLogc(title = "用户改变状态", action = "用户改变状态", actionAdo = "后台用户信息")
	public BaseResult changeState(@RequestBody UserInfoUpdateStateParam params) {
		ValidatorUtils.validate(params);
		UserManageInfo entity = userManageInfoService.getById(params.getId());
		if ( null == entity ) {
			throw new BusinessException(PlatformAdminErrorEnum.USER_NULL);
		}
		if(PlatformAdminConstant.AdminUserState.AUS_Del.getCode().equals(entity.getUserState())) {
			throw new BusinessException(PlatformAdminErrorEnum.USER_NULL);
		}
		if (BaseConstant.YNEnum.YES.getCode().equals(entity.getIsManager()) ) {
			throw new BusinessException(PlatformAdminErrorEnum.USER_IS_MANAGER);
		}
		if(entity.getUserState().equals(params.getState())) {
			return BaseResult.ok();
		}
		entity.setUserState(params.getState());
		entity.addEditParam(AuthContextUtils.getUser());
		userManageInfoService.updateById(entity);
		
		if(!PlatformAdminConstant.AdminUserState.AUS_Open.getCode().equals(entity.getUserState())) {
			userPermissionCacheService.logoutUser(entity.getId());
		}
		
		return BaseResult.ok();
	}
	
	
	@PostMapping("/setPassWord")
	@ApiOperation(value="用户设置密码",response = BaseResult.class)
	public BaseResult setPassWord(@RequestBody UserInfoUpdatePasswordParam params) {
		ValidatorUtils.validate(params);
		UserManageInfo entity = userManageInfoService.getById(params.getId());
		if ( null == entity ) {
			throw new BusinessException(PlatformAdminErrorEnum.USER_NULL);
		}
		if ( !PlatformAdminConstant.AdminUserState.AUS_Open.getCode().equals(entity.getUserState()) ) {
			throw new BusinessException(PlatformAdminErrorEnum.USER_NULL);
		}
		String[] passwords = PasswordUtils.getMd5Password(params.getPassword());
		entity.setPassword(passwords[0]);
		entity.setSalt(passwords[1]);
		entity.addEditParam(AuthContextUtils.getUser());
		userManageInfoService.updateById(entity);
		return BaseResult.ok();
	}





	
}
